package com.dou.cloud.bridge.redis.handler;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @Author daizl
 * @Date 2024 05 13 13 07
 **/
@Component
public class RedissonFactory implements InitializingBean {

    @Resource
    private List<AbstractDistributedLockHandler> handlers;

    private final Map<Integer, AbstractDistributedLockHandler> strategyMap = MapUtil.newConcurrentHashMap();


    /**
     * 根据type获取handler
     *
     * @param type 类型
     * @return handler 策略处理类
     */
    public AbstractDistributedLockHandler getStrategy(Integer type) {
        return strategyMap.get(type);
    }

    /**
     * 注册handler
     *
     * @param handler 策略处理类
     */
    public void register(AbstractDistributedLockHandler handler) {
        if (handler == null || handler.getType() == null) {
            return;
        }
        strategyMap.put(handler.getType(), handler);
    }

    @Override
    public void afterPropertiesSet() {
        // 初始化bean后注册所有handler
        if (CollUtil.isNotEmpty(handlers)) {
            handlers.forEach(this::register);
        }
    }
}
